<template>
  <form-dialog v-model="dialogVisible" :title="title" @save="save()" @close="close">

  <el-form ref="ruleFormRef" :model="dataForm" :rules="rules" label-width="80px">
      <el-form-item v-if="type==1" label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item v-if="type==1" label="课时类型" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选择类型" @change="changeClassHandle">
          <el-option v-for="item in $Const.classTypeList" :key="item.code" :label="item.name" :value="item.code"/>
        </el-select>
      </el-form-item>
      <el-form-item v-if="type==2" label="章节目录" prop="type">
        <el-select
            v-model="data.moreCourse"
            placeholder="请选择章节目录"
            @change="changeMoreCourse"
        >
          <el-option v-for="item in chapterList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <!-- 选择年份 -->
      <el-form-item label="选择年份" v-if="type==2">
        <el-date-picker
        v-model="data.changeDate"
        type="year"
        placeholder="请选择年份"
        format="YYYY"
        @change="changeDateHandle"
        :size="size"
      />
       </el-form-item>
      <el-form-item v-if="type==1" label="课时名称" prop="typeAssoId">
        <el-select v-model="dataForm.typeAssoId" collapse-tags placeholder="请选择课时名称"
                   popper-class="my-popper-class" @change="changeTypeAssoHandle">
          <el-option v-for="item in data.resourceList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item v-else label="课时名称" prop="typeAssoId">
        <el-select v-model="moreCourseArr" collapse-tags multiple placeholder="请选择课时名称"
                   popper-class="my-popper-class" @change="changeTypeMore">
          <el-option v-for="item in fillterArr" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <el-checkbox v-if="data.moreCourse" v-model="isAllSelect" @change="isAllSelectHandle" style="margin-left: 20px;">全选</el-checkbox>
      </el-form-item>
      <template v-if="needDoc()&&type==1">
        <el-form-item label="课时课件" prop="resDocId">
          <el-input v-model="dataForm.resDocName" disabled/>
        </el-form-item>
        <el-form-item label="课时题库" prop="resQuestionId">
          <el-input v-model="dataForm.resQuestionName" disabled/>
        </el-form-item>
      </template>
    </el-form>
  </form-dialog>
</template>

<script setup>
import {defineEmits, defineProps, reactive, ref, watch} from "vue"
import {publicApi} from "@/api/public"
import {Constant as $Const} from "../../../../../utils/constant"

let props = defineProps({
  modelValue: {
    type: Boolean,
    require: true,
    default: false
  },
  title: {
    type: String,
    default: ""
  },
  dataForm: {
    type: Object,
    default: {}
  },
  course: {
    type: Object,
    default: {}
  },
  save: {
    type: Function,
    default: () => {
      return Function;
    }
  },
  type: {
    type: Number,
    default: 1

  }, chapterList: {
    type: Array,
    default: []
  }
});


let data = reactive({
  resourceList: [],
  docList: [],
  questionList: [],
  moreCourse: '',
  changeDate: ''
})

const rules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  typeAssoId: [{ required: true, message: '请选择课时名称', trigger: 'blur' }],
})

const dialogVisible = ref(props.modelValue);//显示弹窗
const title = ref(props.title);//弹窗标题

let emits = defineEmits(['update:modelValue', 'save']);
// 选择年份
const changeDateHandle = (e) => {
  console.log( data.resourceList)
  data.changeDate = e
  let year = data.changeDate.getFullYear()
  if( year){
    fillterArr.value =  data.resourceList.filter(item => item.chapterCatalog == data.moreCourse)
    fillterArr.value = fillterArr.value.filter(item => item.year == year)
  }else{
    fillterArr.value = data.resourceList.filter(item => item.chapterCatalog == data.moreCourse)
  }
  isAllSelect.value=false
  moreCourseArr.value = []
}
//保存表单方法
const save = () => {
  let dataForm = props.dataForm
  if (props.type == 2) {
    for (let i = 0; i < moreCourseArr.value.length; i++) {
      addMoreCourse(moreCourseArr.value[i])
    }
    return
  }
  let saveData = {}
  saveData.id = props.dataForm.id
  saveData.name = dataForm.name
  saveData.type = dataForm.type
  saveData.parent = dataForm.parent
  saveData.isEdit = dataForm.isEdit
  let classTypeList = $Const.classTypeList
  let targetItem = classTypeList.find(item => item.code == dataForm.type)

  if (targetItem) {
    saveData.typeName = targetItem.name
  }
  saveData.typeAssoId = dataForm.typeAssoId
  let assoItem = data.resourceList.find(item => item.id == dataForm.typeAssoId)
  if (assoItem) {
    saveData.typeAssoName = assoItem.name
  }
  if (needDoc()) {
    saveData.docId = dataForm.resDocId
    saveData.docName = dataForm.resDocName
    saveData.questionId = dataForm.resQuestionId
    saveData.questionName = dataForm.resQuestionName
  }
  emits('save', saveData);
}
// 循环添加课程
const addMoreCourse = (id) => {
  let dataForm = props.dataForm
  let saveObj = {}
  let assoItem = data.resourceList.find(item => item.id == id)
  saveObj.name = assoItem.name
  saveObj.type = 'video'
  saveObj.parent = dataForm.parent
  saveObj.isEdit = dataForm.isEdit
  saveObj.typeName = '视频'
  saveObj.typeAssoId = assoItem.id
  if (assoItem) {
    saveObj.typeAssoName = assoItem.name
  }
  saveObj.docId = assoItem.docId
  saveObj.docName = assoItem.docName
  saveObj.questionId = assoItem.questionId
  saveObj.questionName = assoItem.questionName
  emits('save', saveObj);
}
const close = () => {
  moreCourseArr.value = []
  data.moreCourse = ''
  emits('update:modelValue', false);
}
const changeTypeAssoHandle = () => {
  let dataForm = props.dataForm
  let assoItem = data.resourceList.find(item => item.id == dataForm.typeAssoId)
  props.dataForm.resQuestionId = assoItem.bankId
  props.dataForm.resQuestionName = assoItem.bankName
  props.dataForm.resDocId = assoItem.docId
  props.dataForm.resDocName = assoItem.docName
}
const changeTypeMore = (e) => {
  if(e.length== fillterArr.value.length){
    isAllSelect.value=true
  }else{
    isAllSelect.value=false
  }
  console.log(e)
}
const changeClassHandle = () => {
  ajaxListClass()
}

const ajaxListClass = () => {
  let type = props.dataForm.type
  if (!type) {
    type = 'video'
  }
  ajaxListByCode(type, 'resourceList')
}

const initDocAndQuestion = () => {
  ajaxListByCode('doc', 'docList')
  ajaxListByCode('question', 'questionList')
}

const ajaxListByCode = (code, listCode) => {
  console.log(listCode)
  let classTypeList = $Const.classTypeList
  let targetItem = classTypeList.find(item => item.code == code)
  let paramMap = {courseType: props.course.categoryId, publishedFlag: 1}
  publicApi(targetItem.url, 'post', paramMap).then((res)=> {
    console.log(res)
    data[listCode] = res.rows
    if (listCode == 'resourceList') {
      fillterArr.value = data.resourceList
    }
  })
}

const needDoc = () => {
  let type = props.dataForm.type
  return type === 'video' || type === 'live' || type === 'offline'
}

//监听value
watch(() => props.modelValue, (value, o) => {
  dialogVisible.value = value
  if (value) {
    ajaxListClass()
    initDocAndQuestion()
  }
});

watch(() => props.dataForm, (value, o) => {
  dialogVisible.value = value
});
let moreCourseArr = ref([])
let fillterArr = ref([])
const changeMoreCourse = (e) => {
  isAllSelect.value=false
  moreCourseArr.value = []
  if(data.changeDate){
    let year = data.changeDate.getFullYear()
    fillterArr.value = data.resourceList.filter(item => item.year == year)
    fillterArr.value = fillterArr.value.filter(item => item.chapterCatalog == data.moreCourse)
  }else{  
    fillterArr.value = data.resourceList.filter(item => item.chapterCatalog == data.moreCourse) 
  }
  isAllSelectHandle()

  // fillterArr.value = data.resourceList.filter(item => item.chapterCatalog == data.moreCourse)
  // moreCourseArr.value = fillterArr.value.map(item => item.id)


  // data.resourceList.forEach(item => {
  //   if (item.chapterCatalog == data.moreCourse) {
  //     moreCourseArr.value.push({
  //       resQuestionId: item.bankId,
  //       resQuestionName: item.bankName,
  //       resDocId: item.docId,
  //       resDocName: item.docName,
  //       id: item.id
  //     })
  //   }
  // })
}
const isAllSelect = ref(false)
const isAllSelectHandle = () => {
  if (isAllSelect.value) { 
  moreCourseArr.value = fillterArr.value.map(item => item.id)

  } else {
    moreCourseArr.value = []
  }
}
</script>
<style lang="scss" scoped>
.el-input__wrapper {
  height: 200px;
}
</style>
